package com.cy.pj.goods.dao;

import jdk.nashorn.internal.runtime.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Repository
public class DefaultGoodsDao implements GoodsDao {

    @Autowired
    private DataSource dataSource;

    Map<String, Object> rowMap(ResultSetMetaData rsmd, ResultSet rs) throws SQLException {
        Map<String, Object> map = new HashMap<>();
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            map.put(rsmd.getColumnName(i), rs.getObject(rsmd.getColumnName(i)));
        }
        return map;
    }

    @Override
    public List<Map<String, Object>> findGoods() {
        List<Map<String, Object>> list = new ArrayList<>();
        try (Connection conn = dataSource.getConnection()) {
            String sql = "select * from tb_goods";
            Statement s = conn.createStatement();
            ResultSet rs = s.executeQuery(sql);

            ResultSetMetaData rsmd = rs.getMetaData();//获取结果集中的元数据

            while (rs.next()) {
                HashMap<String, Object> object = new HashMap<>();
//                object.put("id", rs.getInt(1));
//                object.put("name", rs.getString(2));
//                object.put("remark", rs.getString(3));
//                object.put("createdTime", rs.getTimestamp(4));

                list.add(rowMap(rsmd, rs));

            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询异常,{}", e.getMessage());

        }
        return list;
    }
}
